
use regex::Regex;

// 国内手机号的正则表达式
 const REGEX_PHONE:&str = r"^1(3\d|4[5679]|5[0-35-9]|66|7[0135-8]|8\d|9\d)\d{8}$";
// 国内外电话都适配的正则
//  const REGEX_MOBILE:&str = r"^(?:\+?(\d{1,3}))?[-. ]?(?:\(?(\d{1,4})\)?[-. ]?)?(\d{1,4})[-. ]?(\d{1,4})[-. ]?(\d{1,9})$";
// 国内固话号码的正则
const REGEX_MOBILE_PHONE:&str = r"^(0(10|2[1-9]|[3-9]\d{2}))?[1-9]\d{6,7}$";
// 是否是数字
const REGEX_IS_NUMBER:&str = r"^-?[0-9]+$";


/** 
 * 电话号码脱敏
*/
pub fn desen_phone(phone:&str) -> String{

    if is_phone(phone) {
        println!("是电话号码");
        let phone_len = phone.len();
        if phone_len<8 {
            return phone.to_string();
        }else {
            println!("开始截");
            let mut desen_str = String::with_capacity(phone_len);
            desen_str.push_str(&phone[0..3]);
            for _ in 0..(phone_len-7) {
                desen_str.push_str("*");
            }
            desen_str.push_str(&phone[(phone_len-4)..phone_len]);

            return desen_str;
        }
    }

    return phone.to_string();
}


/**
 * 把数字字符串转换成数值类型
 */
pub fn string_to_number(content:&str) -> i32{
    if is_number(content) {
       return  content.parse().unwrap_or(0);
    }
    return 0;
}


/**
 * 号码规整
 */
pub fn format_phone(number: &str) -> String{

    let mut number01:String = number.to_string(); 

    if number01.is_empty() {
       return number01;
    }
  
    if number.starts_with("+86") {
        number01 = number01.replacen(r"+86", "",1);
    }

    if number01.starts_with(" 86") {
        number01 = number01.replacen(" 86", "",1);
    }

    if number01.starts_with("86") {
        number01 = number01.replacen("86", "",1);
    }

    if number01.starts_with("0") {
        number01 = number01.replacen("0", "",1);
    }

    println!("输出数据number：{}", number01);

    if is_phone(&number01){
        return number01;
    }else {
        let number02 = "0".to_string() + &number01;
        if is_mobile_phone(&number02) {
            return number02;
        }else {
            return number01;
        }
    }

}


/**
 * 是否是数字
 */
pub fn is_number(content: &str) -> bool{
    if content.is_empty(){
        return false;
    }

    return regex_ifmatch_str(content, REGEX_IS_NUMBER);
}


/**
 * 是否是手机号码
 */
pub fn is_mobile_phone(mobile:&str) -> bool{
    return regex_ifmatch_str(mobile, REGEX_MOBILE_PHONE);
}

// 是否是手机号码
pub fn is_phone(phone: &str) -> bool{
    return regex_ifmatch_str(phone, REGEX_PHONE);
}

// 正则匹配 
pub fn regex_ifmatch_str(content: &str, regex_str: &str) -> bool{

    let re = Regex::new(regex_str);
    match re {
        Ok(r) => {
             return r.is_match(content);

        },
        Err(_e) => {
            return false;
        },
    };
}

